package com.stlm2.controller;

import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.ConfigDao;
import com.stlm2.dems.dao.UserCardsDao;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.*;


import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.service.AccountService;
import com.stlm2.util.Convert;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by songfangyuan on 2017/5/25.
 */
@Controller
@RequestMapping("/testC")
public class TestController {
     @Resource
     private ConfigService configService;
    @Resource
    private ConfigDao configDao;
    @Resource
    private Memcached memcached;
    @Resource
    private AccountService accountService;
    @Resource
    private UserService userService;
    @Resource
    private AccountDao accountDao;
    @Resource
    private UserDao userDao;
    @Resource
    private UserCardsDao userCardsDao;
    @Resource
    private GoodsOrderService goodsOrderService;
    @Resource
    private PurchaseOrderService purchaseOrderService;
    @Resource
    private DdmGoodsService ddmGoodsService;
    @Resource
    private CommissionService commissionService;
    @Resource
    private SeckillGoodsService seckillGoodsService;

//    @ResponseBody
//    @RequestMapping("/makeAreaSort.json")
//    public String  makeAreaSort(ModelMap model){
//        //areaService.makeSort();
//        List<Area>areaList=areaDao.getBySortAll();
//        System.out.println("地址数"+areaList.size());
//        return CodeContent.getModelByCode(1,"sucess", model);
//    }

//    @ResponseBody
//    @RequestMapping(value="/cityPosition.json",produces="application/json;charset=UTF-8")
//    public String CityPosition(){
//        String date="";
//        date=areaService.CityPosition();
//        return date;
//    }
    @ResponseBody
    @RequestMapping("/setMemcach.json")
    public String setMemcachValue(String companyCode,String date){
        String key="king";
        memcached.set(key,60*5,date);
        System.out.println("key-value：king-"+date);
        return   CodeContent.getModelByCode(1,"sucess",null);
    }
    @ResponseBody
    @RequestMapping("/getMemcach.json")
    public String getMemcachValue(String companyCode){
        String key="king";
        memcached.get(key);
        System.out.println("key-value：king-"+(String) memcached.get(key));
        return   CodeContent.getModelByCode(1,"sucess",null);
    }


    //redis 存入config对象（业务员提点比率）
    @ResponseBody
    @RequestMapping(value="/saveSaleManRate.json",produces="application/json;charset=UTF-8")
    public String test(String companyCode) {
        Config config = new Config();
        config.setConfigName("SALE_MAN_RATE");
        config.setConfigValue("10");
        List<String> list = new ArrayList<String>();
        list.add("configName");

        configDao.addIntoRedis(config, list);
        return CodeContent.getModelByCode(1,"",null);
    }

   @ResponseBody
   @RequestMapping(value="/addAgent.json",produces="application/json;charset=UTF-8")
    public String addAgent(String companyCode,String token, String userName,String realName,String IDCode,String phone,String password,String agencyTypeValue,String softMoney,String technologyMoney,String provinceId,String cityId,String countyId,String bilv){
//        token="9F3F037F7EE71A511D61582CB354B4FC";
//        userName="A";
//        realName="A2";
//        IDCode="410125556255835";
//        password="1234567";
//        phone="18838998708";
//        agencyTypeValue="2";
//        softMoney="80000";
//        technologyMoney="78000";
//        provinceId="16";
//        cityId="152";
//        countyId="1363:1364:1365:1366:1367:1368:1369:2864";
//        bilv="0.001";
//        String data=  agentService.addAgent(token,userName,realName,IDCode,phone,password,agencyTypeValue,softMoney,technologyMoney,provinceId,cityId,countyId,bilv);
        return  null;
    }

    @ResponseBody
    @RequestMapping(value="/testConfig.json",produces="application/json;charset=UTF-8")
    public String testConfig(String companyCode) {
        Config config = new Config();
        config=configDao.getById(2);
        System.out.println(config.getConfigName()+"=============");

        return CodeContent.getModelByCode(1,"",null);
    }

    @ResponseBody
    @RequestMapping(value="/testSalary.json",produces="application/json;charset=UTF-8")
    public String testSalary(String companyCode) {

//           agentSalaryService.saveEveryMonthMoney();
        return CodeContent.getModelByCode(1,"",null);
    }

    @ResponseBody
    @RequestMapping(value="/fanJiFen.json",produces="application/json;charset=UTF-8")
    public String fanJiFen(String companyCode,String passWord){

        if(com.stlm2.util.StringUtils.isNullOrEmpty(passWord)){
            return CodeContent.getModelByCode(0,"请输入密码口令",null);
        }
        if("sfyyfs".equals(passWord)){
            //accountService.songJiFen();
            accountService.retPacket();
        }else {
            return CodeContent.getModelByCode(0,"密码口令错误",null);
        }
        ModelMap model=new ModelMap();
        model.put("result","手动发送红包，发放完毕");
        return CodeContent.getModelByCode(1,"手动发送红包，发放完毕",model);

    }
    /*
    * sfy
    * 2017年8月4日10:04:15
    * 将数据进行更新
    * 1 还是以用户当前的cdd和sdd为准，计算处一共要送的积分
    * 2 计算已经送出去的积分
    * 3 进行扣除1 中的cdd 和sdd
    * 4 用户做单统计算出用户一共消费的金钱（多条记录边为一条）
    * */
    @ResponseBody
    @RequestMapping("/dateUpdate.json")
    public void dateUpdate(String companyCode){
//         userService.dataUpdate();

    }

    /**
     *用户积分清零
     * ffl
     * 2017年8月8日18:09:58
     * @return
     */
    @ResponseBody
    @RequestMapping("/cleanUserIntegral.json")
    public  String updateAllUserIntegral(String companyCode){
       // userIntegralService.updateAllUserIntegral();
        return CodeContent.getModelByCode(1,"",null);
    }


//    @ResponseBody
//    @RequestMapping("/sort.json")
//    public String testSort(){
//        List<Integer> list=new ArrayList<Integer>();
//        for (int i=2;i<10;i++){
//            int k=i%2;
//            if(k==0)
//                list.add(i);
//        }
//        for (int i=2;i<10;i++){
//            int k=i%2;
//            if(k==1)
//                list.add(i);
//        }
//
//        for (int i=0;i<list.size();i++){
//            System.out.println("未排序"+list.get(i));
//        }
//        Collections.reverse(list);
//        for (int i=0;i<list.size();i++){
//            System.out.println("排序:reverse"+list.get(i));
//        }
//        Collections.sort(list);
//        for (int i=0;i<list.size();i++){
//            System.out.println("排序:sort"+list.get(i));
//        }
//        return CodeContent.getModelByCode(1,"",null);
//    }


    @ResponseBody
    @RequestMapping(value="/testUserUpper.json",produces="application/json;charset=UTF-8")
    public String setUserUpper(String companyCode){
        return userService.getAndHandUser();
    }
    @ResponseBody
    @RequestMapping(value="/testUserLevel.json",produces="application/json;charset=UTF-8")
    public String updateUserLevel(String companyCode,String userId){
        if(!NumberUtils.isDigits(userId)){
            return CodeContent.getModelByCode(0,"userId 不能为空",null);
        }
        return userService.updateUserLevel(NumberUtils.toInt(userId));
    }

    @ResponseBody
    @RequestMapping(value="/testMessage.json",produces="application/json;charset=UTF-8")
    public String testMessage(String companyCode){
        Long num=new Date().getTime();
        Long num2=num+5;
        //用户提现记录 保存24小时
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();
            for (long i=num;i<num2;i++){
                String key="message:"+i+":"+727+":tixian";
                jedis.set(key,"77");
                jedis.expire(key,86400);
            }
            for (long i=num;i<num2;i++){
                String key="message:"+i+":"+727+":tixianApply";
                jedis.set(key,"77");
                jedis.expire(key,86400);
            }
            for (long i=num;i<num2;i++){
                String key="message:"+i+":"+232+":order";
                jedis.set(key,"1177");
                jedis.expire(key,86400);
            }
            for (long i=num;i<num2;i++){
                String key="message:"+i+":"+727+":redPackets";
                jedis.set(key,"77");
                jedis.expire(key,86400);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            pool.returnResource(jedis);
        }
        return CodeContent.getModelByCode(1,"",null);
    }

    @ResponseBody
    @RequestMapping(value="/partnerCommission.json",produces="application/json;charset=UTF-8")
    public  String  testCommission(String companyCode,String token){
        User user=userDao.getByToken(token);
        if (user==null)
            return CodeContent.getModelByCode(-1,"",null);
        if (user.getId()-4==0) {
            commissionService.partnerLevelCommission();
        }
        return CodeContent.getModelByCode(1,"",null);
    }



    @ResponseBody
    @RequestMapping(value="/testRandom.json",produces="application/json;charset=UTF-8")
    public  void random(String companyCode,int n, int L){
            Random rand = new Random();
            int temp = L;
            for(int i = 1, j; i < n; i++){
                j = rand.nextInt(temp-1) + 1;
                if(j > temp-(n-i)){//保证每个随机数最小为1，那么j就不能大于temp-(n-i)

                    j = temp-(n-i);
                }  else if(j<= 0){
                    j = 1;
                }
                temp -= j;
                System.out.println("+++++++"+j);
            }
            System.out.println("======="+temp);
    }


    @ResponseBody
    @RequestMapping(value="/testRandom2.json",produces="application/json;charset=UTF-8")
    public  String arr(String companyCode,int n, int L){
        Random rand=new Random();
        int[] a=new int[L];
        int k=n/L;
        int M=n%L;
        if(k==1){
          for(int i=0;i<L ;i++){
            a[i]=1;
          }
          for (int i=0;i<M;i++){
             int j= rand.nextInt(L);
              int temp=a[j];
              temp++;
              a[j]=temp;
          }
        }else {
            int v=k/2;
            int t=n-L*v;
            System.out.println("+++++++-----基数"+v);
            for(int i=0;i<L;i++){
                a[i]=v;
            }
            for(int i=0;i<t ;i++){
                int j= rand.nextInt(L);
                int temp=a[j];
                temp++;
                a[j]=temp;
            }
        }

        for(int i=0;i<L;i++){
            System.out.println("========"+a[i]);
        }
        System.out.println("+++++++++++++++++++++++++++++++++++");
       return CodeContent.getModelByCode(1,"",null);
    }


    @ResponseBody
    @RequestMapping(value="/redisFootMarkNum.json",produces="application/json;charset=UTF-8")
    public String getMyRedPacket(String companyCode,String token){
        ddmGoodsService.footMarkNum();
        return CodeContent.getModelByCode(0,"",null);
    }


    @ResponseBody
    @RequestMapping(value="/redPacketByMoney.json",produces="application/json;charset=UTF-8")
    public String redPacketByMoney(String companyCode,String token){
        return  accountService.retPacketByMoney();
    }

    @ResponseBody
    @RequestMapping(value="/testStringArr.json",produces="application/json;charset=UTF-8")
    public String testStringArr(String companyCode,String key2){
        String key=12+":"+2+":"+"";
        String[] val=key.split(":");
        String[] val2=key2.split(":");
        for(int i=0;i<val.length;i++){
            System.out.println("========="+val[i]);
        }
        for(int i=0;i<val2.length;i++){
            System.out.println("++++++++++"+val2[i]);
        }
        return  CodeContent.getModelByCode(1,"",null);
    }


    @ResponseBody
    @RequestMapping(value="/testTime.json",produces="application/json;charset=UTF-8")
    public String testUpdateUserIntegralDetail(String companyCode){
        Date current = new Date();
        Date cancelTime = Convert.beforeDay(current,1);//一天前
        PurchaseOrder param = new PurchaseOrder();
        param.setOrderState(OrderState.Create);
        param.setCreateTime(cancelTime);
        System.out.println("现在时间的前一天时间："+Convert.toFullYMDHMS(cancelTime));
        List<PurchaseOrder> purchaseOrderList = purchaseOrderService.getList(-1, -1, param);
        if (purchaseOrderList != null && purchaseOrderList.size() > 0) {
            for (PurchaseOrder purchaseOrder : purchaseOrderList) {
                System.out.println(purchaseOrder.getId()+"创建时间："+Convert.toFullYMDHMS(purchaseOrder.getCreateTime()));
            }
        }

        return  CodeContent.getModelByCode(1,"",null);
    }



//    /*
//    *zlq 测试大转盘抽奖
//     */
//    @ResponseBody
//    @RequestMapping(value="/testCouJiang",produces="application/json;charset=UTF-8")
//    public  String  slyderAdventures(ModelMap model,String token,String dengJi){
//        if (StringUtils.isEmpty(token)) {
//            return  CodeContent.getModelByCode(-1, "", model);
//        }
//        User loginUser = userDao.getByToken(token);
//        if (loginUser == null) {
//            return  CodeContent.getModelByCode(-1, "", model);
//        }
//        if(loginUser.getUserState().equals(UserState.Invalid)){
//            return  CodeContent.getModelByCode(0, "您的账户已经无效", model);
//        }
//        Activity  activity=activityDao.getByLabel("SLYDER_ADVENTURES");
//        if(activity==null){
//            return CodeContent.getModelByCode(0, "大转盘抽奖活动不存在，请联系管理员", model);
//        }
//        if(activity.getStartTime().getTime()>new Date().getTime()){
//            return CodeContent.getModelByCode(0, "大转盘抽奖活动未开始，请耐心等待", model);
//        }
//        if(activity.getEndTime().getTime()<new Date().getTime()){
//            return CodeContent.getModelByCode(0, "大转盘抽奖活动已经结束，请耐心等待下次活动", model);
//        }
//        if(!activity.getActivityState().equals(ActivityState.Valid)){
//            return CodeContent.getModelByCode(0, "大转盘抽奖活动已经结束，请耐心等待下次活动", model);
//        }
//        Account account=accountDao.getByUserId(loginUser.getId());
//        if(account==null){
//            return CodeContent.getModelByCode(0, "不存在的资金账户", model);
//        }
//        if(account.getAccountState().equals(AccountState.Locked)){
//            return CodeContent.getModelByCode(0, "资金账户已被锁定", model);
//        }
//        Config config=new Config();
//        config.setConfigName("DZP_JIFEN");
//        config=configDao.selectOneFromRedis(config);
//        if(config==null){
//            return CodeContent.getModelByCode(0, "获取积分配置信息失败，请联系管理员.......", model);
//        }
//        if (!NumberUtils.isDigits(config.getConfigValue())) {
//            return CodeContent.getModelByCode(0, "获取积分配置信息失败，请联系管理员.......", model);
//        }
//        int  costJiFen=Integer.parseInt(config.getConfigValue());
//        if(costJiFen<1){
//            return CodeContent.getModelByCode(0, "获取积分配置信息失败，请联系管理员.......", model);
//        }
//        Config couponConfig=new Config();
//        couponConfig.setConfigName("CHOUJIANG_KA");
//        couponConfig=configDao.selectOneFromRedis(couponConfig);
//        if(couponConfig==null){
//            return CodeContent.getModelByCode(0, "获取卡券配置信息失败，请联系管理员.......", model);
//        }
//        UserCoupon userCoupon =new UserCoupon();
//        userCoupon.setUserId(loginUser.getId());
//        userCoupon.setState(1);
//        userCoupon.setCouponId(Integer.parseInt(couponConfig.getConfigValue()));
//        List < UserCoupon> userCouponList=userCouponDao.queryPageView(-1,-1,"query3",userCoupon).getRecords();
//        if(userCouponList.size()>0){
//            costJiFen=0;
//            userCoupon=userCouponList.get(0);
//        }else {
//            userCoupon=null;
//            if(account.getAccountMoney().compareTo(new BigDecimal(costJiFen))!=1){
//                return CodeContent.getModelByCode(0, "余额不足", model);
//            }
//        }
//        //防止重复提交
////        Object o = memcached.get(loginUser.getId()+"slyderAdventures");
////        if(o!=null){
////            return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", model);
////        }else {
////            memcached.set(loginUser.getId()+"slyderAdventures",5,"1");
////        }
//        Random random = new Random();
//        int num=random.nextInt(8)+1;
//        if(dengJi!=null){
//            num=Integer.parseInt(dengJi);
//        }
//        JiangPin jiangPin =new JiangPin();
//        jiangPin.setJiangPinType(JiangPinType.SlyderAdventures);
//        jiangPin.setJiangPinState(JiangPinState.Valid);
//        jiangPin.setJiangPinLevelValue(num);
//        jiangPin=jiangPinDao.selectOneFromRedis(jiangPin);
//        if(jiangPin==null){
//            return CodeContent.getModelByCode(0, "无奖品，抽奖失败，请联系管理员.......", model);
//        }
//        //进入领奖处理的方法
//        model=activityService.payoffWindow( model,loginUser,jiangPin, userCoupon,account,costJiFen);
//
//        return  new JSONObject(model).toString();
//    }
//
//


    @ResponseBody
    @RequestMapping(value="/testVirtualMessage.json",produces="application/json;charset=UTF-8")
    public  String virtualMessage(String companyCode){
        Config config4=new Config();
        config4.setConfigName("BIG_RED_PACKET_INTERVAL");
        Config config5=configDao.selectOneFromRedis(config4);
        if(config5!=null) {//随机大红包
            String moneyInterval=config5.getConfigValue();
            String[] moneyStr=moneyInterval.split("--");
            if(moneyStr.length==2) {

                Integer small = Integer.valueOf(moneyStr[0]);
                Integer big = Integer.valueOf(moneyStr[1]);
                Random random=new Random();
                JedisPool pool = null;
                Jedis jedis = null;
                try {
                    pool = RedisClient.getPool();
                    jedis = pool.getResource();
                    for (int i=0;i<30;i++){
                        Integer bigRedPacket= random.nextInt(big-small)+small;
                        Long time=new Date().getTime();
                        String key2 = "message:" + time + ":" + -i + ":redPackets:big";
                        jedis.set(key2, bigRedPacket.toString());
                        jedis.expire(key2, 43200);
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    pool.returnResource(jedis);
                }

            }
        }
        return CodeContent.getModelByCode(1,"",null);
    }


    @ResponseBody
    @RequestMapping(value="/userCard.json",produces="application/json;charset=UTF-8")
    public String updateUserCardsState(String companyCode,String token){
        User user=userDao.getByToken(token);
        if(user==null){
            return CodeContent.getModelByCode(-1,"",null);
        }
        List<UserCards> timeOutList=userCardsDao.timeOutCards(user.getId());
        for (UserCards userCards:timeOutList) {
            System.out.println("A卡券id："+userCards.getId()+"====卡券状态："+userCards.getCardsState().toString());
        }
        userCardsDao.updateStateToDue(user.getId());
        System.out.println("================================");
        List<UserCards> timeOutList2=userCardsDao.timeOutCards(user.getId());
        for (UserCards userCards:timeOutList2) {
            System.out.println("B卡券id："+userCards.getId()+"====卡券状态："+userCards.getCardsState().toString());
        }

        return CodeContent.getModelByCode(1,"",null);
    }


    @ResponseBody
    @RequestMapping(value="/finishOrder.json",produces="application/json;charset=UTF-8")
    public String finishOrder(String companyCode,String token){
        User user=userDao.getByToken(token);
        if(user==null){
            return CodeContent.getModelByCode(-1,"",null);
        }
        if(user.getId()-4==0){
            goodsOrderService.finishOrder();
        }


        return CodeContent.getModelByCode(1,"",null);
    }

    @ResponseBody
    @RequestMapping(value="/testDate.json",produces="application/json;charset=UTF-8")
    public String testDate(String companyCode,String seckillDate){
        System.out.println(seckillDate);


        return CodeContent.getModelByCode(0,"ok",null);
    }

    @ResponseBody
    @RequestMapping(value="/seckillCancel.json",produces="application/json;charset=UTF-8")
    public String testDate(String companyCode){
        seckillGoodsService.cancelOrderThread();


        return CodeContent.getModelByCode(0,"ok",null);
    }
}







